const { login } = require('../controller/user');
const { SuccessModel, ErrorModel } = require('../model/resModel');
const { set } = require('../db/redis');

const handlerUserRouter = async (req, res) => {
  const method = req.method;

  // 登录
  if (method === 'POST' && req.path === '/api/user/login') {
    const username = req.postData.username || '';
    const password = req.postData.password || '';
    const result = await login(username, password);
    if (result.length && result[0].username) {
      // 设置 session
      req.session.username = result[0].username;
      req.session.realname = result[0].realname;
      // 同步到 redis 中
      set(req.sessionId, req.session);
      return new SuccessModel('登录成功');
    } else {
      return new ErrorModel('登录失败');
    }
  }

  // // 登录验证测试
  // if (method === 'GET' && req.path === '/api/user/login-test') {
  //   if (req.session.username) {
  //     return new SuccessModel({
  //       session: req.session
  //     });
  //   }
  //   return new ErrorModel('还没登录');
  // }
}

module.exports = handlerUserRouter;
